<?php
/**
 * Created by ljhint on 2022/10/7.
 *
 * 此引用的是卢健会之前写的脚本：因现在付款都是用这个酷卡公众号，且支付也是用的这个商户号。
 * 暂时屏蔽退款的部分，其它的暂用这个，后面再根据需求进行重构
 *
 *
 */

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\XcUser;
use App\Models\XcUserXiche;
use App\Models\XcUserRecharge;
use App\Models\XcSiteOrder;
use Illuminate\Http\Request;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Redis;

class WechatController extends Controller
{

	private $configWechat = [];
	public function __construct()
	{
		$this->configWechat = ['app_id'  => config('wechat.payment.default.app_id'),
						        'mch_id'        => config('wechat.payment.default.mch_id'),
						        'key'           => config('wechat.payment.default.key'),
						        'cert_path'     => config('wechat.payment.default.cert_path'),
						        'key_path'      => config('wechat.payment.default.key_path'),
						        'rsa_public_key_path' => config('wechat.payment.default.rsa_public_key_path')
							];
	}
	/**
     * getUserInfo 获取微信用户信息
     * Created by ljhint on 2022/04/14
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getUserInfo(Request $request)
    {
        $openid = null;
        if($request->get('code')){
            $client 	= new Client();
            $code 		= $request->get('code');
            $appid 		= 'wx2e9856682e2666f8';
            $secret 	= '4869dd16c125c8bc98f8c352fb9352de';
            $url 		= 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
            $res 		= $client->request('GET', $url);
            $html 		= json_decode((string)$res->getBody(),true);

            if (isset($html['errmsg'])) {
                return response()->json(['code' => -1, 'msg' => $html['errmsg']]);
            }

            $openid = $html['openid'];
        }

        $openid = $openid??$request->get('openid');
        if (!$openid) {
            return response()->json(['code' => -1, 'msg' => 'openid无法获得']);
        }
        //通过 openid 查找用户数据
        $user = XcUserXiche::where('openid', $openid)->first();

        if ($user !== null) {
            Redis::setex($user->api_token, 1800, json_encode($user));//30分钟有效期
        } else {
        	$token                     = Str::random(60);
            $user['openid']            = substr($openid, 0, 30);
            $user['nickname']          = "";
            $user['headimgurl']        = "";
            $user['truename']          = '';
            $user['mobile']            = '';
            $user['money']             = 0;
            $user['userpoints']        = 0;
            $user['fast_member_exp']   = null;
            $user['fine_member_exp']   = null;
            $user['fast_washing_num']  = 0;
            $user['fine_washing_num']  = 0;
            $user['status']            = 0;
            $user['money_history']     = 0;
            $user['source']      = 'ym';
            $user['api_token']         = '9ac9fd8c878492918488ec4a8858ab306d2fa4daadcbdda03a6ec127a5ws4b69';//临朝api_token，方便临时用户可以查看站点列表

        	//$user = XcUserXiche::create($data);
            //Redis::setex($user->api_token , 1800 , json_encode($user));//30分钟有效期
        }

        return response()->json(['code' => 0, 'msg' => '成功返回', 'data' => $user]);
    }

    /**
     * 解析用户的手机号码
     */ 
    public function getwxmobile(Request $request)
    {

        if($request->get('code')){

            $client = new Client();
            $appid = 'wx2e9856682e2666f8';
            $secret = '4869dd16c125c8bc98f8c352fb9352de';
            $res = $client->request('GET', 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret);
            $html = json_decode((string)$res->getBody(),true);
            
            $access_token = $html['access_token'];
            $code = $request->get('code');

            $phoneRes = $client->post('https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$access_token,[
                'json' => ['code'=>$code]
            ]);
            $phoneArr = json_decode((string)$phoneRes->getBody(),true);
            return response()->json(['code' => 0, 'msg' => 'success', 'data' => $phoneArr]);
        }
        return response()->json(['code'=> -1,'msg' => 'code不存在']);
    }


    private function payment()
    {
        return Factory::payment($this->configWechat);
    }

    /**
     * 获得订单号
     * Created by tommy on 2023/10/30
     * @param $prefix  JJ/HK : 捷洁/嗨卡
     * @return string;
     *
     */
    public function OrderSN($prefix = 'JJ')
    {
        $order_sn = $prefix.date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        return $order_sn;
    }

    /**
     * payJssdk 页面支付
     * Created by ljhint on 2022/10/27
     * @param $openid
     * @param $total_fee
     * @param $notify_url
     * @param string $prefix
     * @return array * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    public function payJssdk($openid, $total_fee, $notify_url, $prefix = "JJ")
    {

        $order_sn = $this->OrderSN($prefix);//前两个字母区分捷洁还是嗨卡

        $order = $this->payment()->order->unify([
            'trade_type' => 'JSAPI',
            'body' => '微信订单支付',
            'out_trade_no' => $order_sn,
            'total_fee' => $total_fee,
            'openid' => $openid,
            'notify_url' => env('APP_URL') . $notify_url
        ]);

        if (isset($order['result_code']) && $order['result_code'] == 'SUCCESS') {
            $json = $this->payment()->jssdk->bridgeConfig($order['prepay_id']);
            return [
                'order_sn' => $order_sn,
                'total_fee' => $total_fee,
                'json' => $json
            ];
        }

        return $order['return_msg'];
    }

    /**
     * 充值微信支付回调
     * @return string
     */
    public function rechargeNotify()
    {
        $response = $this->payment()->handlePaidNotify(function ($message, $fail) {

            Log::info($message);

            $order = XcUserRecharge::where('order_sn', $message['out_trade_no'])->where('pay_status', 1)->first();
            Log::info("wechat notify info:" . $order);

            if (!$order) {
                return true;
            }

            // return_code 表示通信状态，不代表支付状态
            if ($message['return_code'] === 'SUCCESS') {
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {

                    //更新订单状态为了已充值
                    $order_flag = $order->update([
                        'status' => 2,
                        'pay_status' => 2,
                        'pay_time' => date('Y-m-d H:i:s'),
                        'transaction_id' => $message['transaction_id'],
                    ]);

                    Log::info("wechat notify and update recharge result:" . $order_flag);

                    //1充值卡2年卡3季卡4月卡5次卡6单次购买订单
                    if ($order->type == 1 || $order->type == 6) {
                        XcUserRecharge::doRecharge($order, 1);
                    } else {
                        XcUserRecharge::doCardRecharge($order);
                    }

                    return true;
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
        });

        return $response;
    }

    /**
     *
     *
     */
    public function xcxqrcode(Request $request)
    {
        /*
        $appid      = 'wx2e9856682e2666f8';
        $secret     = '4869dd16c125c8bc98f8c352fb9352de';
        $url        = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
        $result     = file_get_contents($url);
        $html       = json_decode($result,true);
        Log::info($html);
        $access_token = $html['access_token'];
        return $html;
        */
        $access_token ='74_VfsCfcbWZG6OowLNctgrDjWxL2gDZfXlXeQ6wqqCDT3Xm9atIBIxrsDtYt4cYyXMtNSXNXJlH23EdlFm4rPTW8q5BoMHRJJAYWTu2q5FcIlQpYZg1ln2fcyROkMQRNiABAMNJ';



        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;

        $param = [
                'scene'         => 'open_sn=jj10029393',
                'page'          => 'packageA/pages/choice/index',
                'width'         => 500,
                'env_version'   => 'develop',
                'auto_color'    => true
                ];

        $result = $this->sendCmd($url,json_encode($param));//请求微信接口
        $errcode = json_decode($result,true)['errcode'];
        $errmsg = json_decode($result,true)['errmsg'];
        if($errcode) {
            return response()->json(['code'=> -1,'msg' => 'failed', 'data' =>$errcode]);
        }
        $filename = 'xcx'.time().'.png';
        $file = '/mnt/wwwroot/xiche.baiche.com.cn/public/xcxqrcode/'.$filename;
        $res = file_put_contents($file,$result);//将微信返回的图片数据流写入文件
        if($res===false){
            return response()->json(['code' => -1, 'msg' => '生成二维码失败']);
        }else{
            return response()->json([
                'url'=>'https://xiche.baiche.com.cn/'.$filename,//cloud.com是我的域名
                ]);
        }
        //$res = $client->post($url, $json_param);
        //返回值

        //return response()->json(['code'=> 0,'msg' => '成功找到', 'data' =>$img_base64]);


    }

    //开启curl post请求
    public function sendCmd($url,$data)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:')); //解决数据包大不能提交
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        return $tmpInfo; // 返回数据
    }


    /**
     * refund 退款
     * @param $outTradeNo 1 订单号
     * @param $refundNo 1 商户退款单号
     * @param $fee 1 订单金额
     * @param $refundDesc 1 说明
     */
    public function refund($outTradeNo, $refundNo, $fee, $refundDesc)
    {

        // 参数分别为：订单号、商户退款单号、订单金额、退款金额、其他参数
        return $this->payment()->refund->byOutTradeNumber($outTradeNo, $refundNo, $fee * 100, $fee * 100, [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => $refundDesc,
        ]);
    }

    /**
     * mchPay 企业付款到用户零钱
     * Created by ljhint on 2020/1/16
     * @param $openid
     * @param $amount
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    /*
    public function mchPay($openid,$amount)
    {
        return $this->payment()->transfer->toBalance([
            'partner_trade_no' => date('YmdHis').str_shuffle(time()),
            'openid' => $openid,
            'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
            're_user_name' => '小卢', // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
            'amount' => $amount, // 企业付款金额，单位为分
            'desc' => '阅读返利', // 企业付款操作说明信息。必填
        ]);
    }
    */

	/**
	 * toBankCard 付款到银行卡
	 * Created by ljhint on 2022/12/05
	 * @param $arr ['partner_trade_no','enc_bank_no','enc_true_name','bank_code','amount','desc']
	 * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
	 * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
	 * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
	 * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
	 * @throws \GuzzleHttp\Exception\GuzzleException
	 */

	/*
	public function toBankCard($arr)
	{
		return $this->payment()->transfer->toBankCard($arr);
    }
    */

	/**
	 * queryBankCardOrder 查询付款到银行卡的订单
	 * Created by ljhint on 2022/12/05
	 * @param $partnerTradeNo
	 * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
	 * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
	 * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
	 * @throws \GuzzleHttp\Exception\GuzzleException
	 */

	/*
	public function queryBankCardOrder($partnerTradeNo)
	{
		return $this->payment()->transfer->queryBankCardOrder($partnerTradeNo);
	}
	*/

    /**
     * redpack 发红包
     * Created by ljhint on 2020/9/4
     * @param $openid
     * @param $amount
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    /*
    private function redpack($openid,$amount)
    {
        $redpackData = [
            'mch_billno'   => date('YmdHis').str_shuffle(time()),
            'send_name'    => '转介绍福利',
            're_openid'    => $openid,
            'total_amount' => $amount,  //单位为分，不小于100
            'wishing'      => '感谢谢您的付出',
            'act_name'     => '转介绍福利',
            'remark'       => '百车网',
        ];
        return $this->payment()->redpack->sendNormal($redpackData);
    }
    */

}
